import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class LocalToursPage extends StatefulWidget {
  const LocalToursPage({super.key});

  @override
  State<LocalToursPage> createState() => _LocalToursPageState();
}

class _LocalToursPageState extends State<LocalToursPage> {
  final Dio _dio = Dio();
  List<Map<String, dynamic>> _tours = [];
  List<Map<String, dynamic>> _filteredTours = [];
  bool _isLoading = true;
  String _selectedCategory = '全部';
  String _selectedTab = '人气推荐';
  String _searchQuery = '';

  final List<String> _categories = [
    '全部',
    '一日游',
    '多日游',
    '当地游',
    '自由行',
    '跟团游',
    '攻略群',
  ];
  final List<String> _tabs = ['人气推荐', '四川', '西藏', '云南'];

  @override
  void initState() {
    super.initState();
    _loadTours();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 获取传递的参数
    final args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    if (args != null && args['category'] != null) {
      _selectedCategory = args['category'];
    }
  }

  Future<void> _loadTours() async {
    try {
      setState(() => _isLoading = true);

      final response = await _dio.get(
        'http://localhost:5000/api/tours',
        queryParameters: {
          'limit': 20,
          'sortBy': 'soldCount',
          'sortOrder': 'desc',
        },
      );

      if (response.statusCode == 200 && response.data['success']) {
        setState(() {
          _tours = List<Map<String, dynamic>>.from(response.data['data']);
          _filterTours();
          _isLoading = false;
        });
      }
    } catch (e) {
      print('加载旅游商品失败: $e');
      setState(() => _isLoading = false);
    }
  }

  void _filterTours() {
    _filteredTours =
        _tours.where((tour) {
          // 分类筛选
          bool categoryMatch =
              _selectedCategory == '全部' ||
              tour['category'] == _selectedCategory;

          // 搜索筛选
          bool searchMatch =
              _searchQuery.isEmpty ||
              tour['title'].toString().toLowerCase().contains(
                _searchQuery.toLowerCase(),
              ) ||
              tour['destination'].toString().toLowerCase().contains(
                _searchQuery.toLowerCase(),
              );

          // 标签筛选
          bool tabMatch =
              _selectedTab == '人气推荐' ||
              tour['destination'].toString().contains(_selectedTab);

          return categoryMatch && searchMatch && tabMatch;
        }).toList();
  }

  void _showTourDetails(Map<String, dynamic> tour) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _buildTourDetailsSheet(tour),
    );
  }

  Widget _buildTourDetailsSheet(Map<String, dynamic> tour) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.8,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          // 拖拽条
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.symmetric(vertical: 12),
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),

          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 产品图片
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: Image.network(
                      tour['image'] ?? '',
                      width: double.infinity,
                      height: 200,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: double.infinity,
                          height: 200,
                          color: Colors.grey[200],
                          child: const Icon(
                            Icons.image_not_supported,
                            size: 50,
                          ),
                        );
                      },
                    ),
                  ),

                  const SizedBox(height: 16),

                  // 标题和价格
                  Text(
                    tour['title'] ?? '',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  const SizedBox(height: 8),

                  if (tour['subtitle'] != null && tour['subtitle'].isNotEmpty)
                    Text(
                      tour['subtitle'],
                      style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                    ),

                  const SizedBox(height: 16),

                  Row(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          const Text(
                            '¥',
                            style: TextStyle(
                              color: Colors.red,
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '${tour['price']}',
                            style: const TextStyle(
                              color: Colors.red,
                              fontSize: 28,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 8),
                      if (tour['originalPrice'] != null &&
                          tour['originalPrice'] > tour['price'])
                        Text(
                          '¥${tour['originalPrice']}',
                          style: const TextStyle(
                            color: Colors.grey,
                            fontSize: 16,
                            decoration: TextDecoration.lineThrough,
                          ),
                        ),
                    ],
                  ),

                  const SizedBox(height: 20),

                  // 产品信息
                  _buildInfoRow('目的地', tour['destination'] ?? ''),
                  _buildInfoRow('游玩天数', tour['duration'] ?? ''),
                  _buildInfoRow('分类', tour['category'] ?? ''),
                  _buildInfoRow(
                    '评分',
                    '${tour['rating'] ?? 4.5} (${tour['reviewCount']} 条评论)',
                  ),
                  _buildInfoRow('已售', '${tour['soldCount']} 份'),

                  const SizedBox(height: 20),

                  // 产品描述
                  const Text(
                    '产品描述',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    tour['description'] ?? '暂无描述',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[700],
                      height: 1.4,
                    ),
                  ),

                  const SizedBox(height: 20),

                  // 亮点
                  if (tour['highlights'] != null &&
                      tour['highlights'].isNotEmpty)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '产品亮点',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 8),
                        ...List.generate(
                          tour['highlights'].length,
                          (index) => Padding(
                            padding: const EdgeInsets.symmetric(vertical: 2),
                            child: Row(
                              children: [
                                const Icon(
                                  Icons.check_circle,
                                  color: Colors.green,
                                  size: 16,
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    tour['highlights'][index],
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 20),
                      ],
                    ),

                  // 立即预订按钮
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () => _showBookingDialog(tour),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text(
                        '立即预订 ¥${tour['price']}',
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: TextStyle(color: Colors.grey[600], fontSize: 14),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            ),
          ),
        ],
      ),
    );
  }

  void _showBookingDialog(Map<String, dynamic> tour) {
    final nameController = TextEditingController();
    final phoneController = TextEditingController();
    final emailController = TextEditingController();
    final remarksController = TextEditingController();
    DateTime selectedDate = DateTime.now().add(const Duration(days: 1));
    int quantity = 1;

    showDialog(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder:
                (context, setDialogState) => AlertDialog(
                  title: const Text('预订信息'),
                  content: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 联系人信息
                        TextField(
                          controller: nameController,
                          decoration: const InputDecoration(
                            labelText: '联系人姓名 *',
                            border: OutlineInputBorder(),
                          ),
                        ),
                        const SizedBox(height: 12),
                        TextField(
                          controller: phoneController,
                          decoration: const InputDecoration(
                            labelText: '联系电话 *',
                            border: OutlineInputBorder(),
                          ),
                          keyboardType: TextInputType.phone,
                        ),
                        const SizedBox(height: 12),
                        TextField(
                          controller: emailController,
                          decoration: const InputDecoration(
                            labelText: '邮箱地址 *',
                            border: OutlineInputBorder(),
                          ),
                          keyboardType: TextInputType.emailAddress,
                        ),
                        const SizedBox(height: 12),

                        // 出发日期
                        InkWell(
                          onTap: () async {
                            final date = await showDatePicker(
                              context: context,
                              initialDate: selectedDate,
                              firstDate: DateTime.now(),
                              lastDate: DateTime.now().add(
                                const Duration(days: 365),
                              ),
                            );
                            if (date != null) {
                              setDialogState(() {
                                selectedDate = date;
                              });
                            }
                          },
                          child: Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '出发日期: ${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-${selectedDate.day.toString().padLeft(2, '0')}',
                                ),
                                const Icon(Icons.calendar_today),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),

                        // 预订数量
                        Row(
                          children: [
                            const Text('预订数量: '),
                            IconButton(
                              onPressed:
                                  quantity > 1
                                      ? () {
                                        setDialogState(() {
                                          quantity--;
                                        });
                                      }
                                      : null,
                              icon: const Icon(Icons.remove),
                            ),
                            Text('$quantity'),
                            IconButton(
                              onPressed: () {
                                setDialogState(() {
                                  quantity++;
                                });
                              },
                              icon: const Icon(Icons.add),
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),

                        TextField(
                          controller: remarksController,
                          decoration: const InputDecoration(
                            labelText: '特殊需求 (可选)',
                            border: OutlineInputBorder(),
                          ),
                          maxLines: 3,
                        ),
                        const SizedBox(height: 16),

                        // 价格总计
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                '总价: ',
                                style: TextStyle(fontSize: 16),
                              ),
                              Text(
                                '¥${(tour['price'] * quantity).toStringAsFixed(0)}',
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.red,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('取消'),
                    ),
                    ElevatedButton(
                      onPressed:
                          () => _submitOrder(
                            tour,
                            nameController.text,
                            phoneController.text,
                            emailController.text,
                            selectedDate,
                            quantity,
                            remarksController.text,
                          ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        foregroundColor: Colors.white,
                      ),
                      child: const Text('确认预订'),
                    ),
                  ],
                ),
          ),
    );
  }

  Future<void> _submitOrder(
    Map<String, dynamic> tour,
    String name,
    String phone,
    String email,
    DateTime startDate,
    int quantity,
    String remarks,
  ) async {
    // 验证输入
    if (name.isEmpty || phone.isEmpty || email.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请填写完整的联系信息'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    try {
      Navigator.pop(context); // 关闭对话框
      Navigator.pop(context); // 关闭详情页

      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(child: CircularProgressIndicator()),
      );

      final response = await _dio.post(
        'http://127.0.0.1:5000/api/orders/tours',
        data: {
          'tourId': tour['_id'],
          'startDate': startDate.toIso8601String(),
          'endDate':
              startDate
                  .add(Duration(days: _getDurationDays(tour['duration'])))
                  .toIso8601String(),
          'quantity': quantity,
          'customerInfo': {
            'name': name,
            'phone': phone,
            'email': email,
            'remarks': remarks.isNotEmpty ? remarks : null,
          },
          'specialRequests': remarks.isNotEmpty ? [remarks] : [],
        },
        options: Options(
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer demo_token', // 需要实际的token
          },
        ),
      );

      Navigator.pop(context); // 关闭加载指示器

      if (response.statusCode == 201 && response.data['success']) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('预订成功！您可以在"我的订单"中查看订单详情'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        throw Exception(response.data['message'] ?? '预订失败');
      }
    } catch (e) {
      Navigator.pop(context); // 关闭加载指示器
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('预订失败: ${e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  int _getDurationDays(String? duration) {
    if (duration == null || duration.isEmpty) return 1;
    // 简单解析天数，如 "3天2夜" -> 3
    final match = RegExp(r'(\d+)天').firstMatch(duration);
    return match != null ? int.parse(match.group(1)!) : 1;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: CustomScrollView(
        slivers: [
          // 应用栏
          SliverAppBar(
            expandedHeight: 200,
            floating: false,
            pinned: true,
            backgroundColor: Colors.blue[700],
            foregroundColor: Colors.white,
            flexibleSpace: FlexibleSpaceBar(
              title: const Text('正在热卖'),
              background: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Colors.blue[700]!, Colors.blue[500]!],
                  ),
                ),
                child: const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(height: 40),
                      Icon(
                        Icons.local_fire_department,
                        size: 48,
                        color: Colors.white,
                      ),
                      SizedBox(height: 8),
                      Text(
                        '发现精彩旅程',
                        style: TextStyle(color: Colors.white70, fontSize: 16),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),

          // 搜索栏
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.all(16),
              child: TextField(
                onChanged: (value) {
                  setState(() {
                    _searchQuery = value;
                    _filterTours();
                  });
                },
                decoration: InputDecoration(
                  hintText: '搜索目的地或产品',
                  prefixIcon: const Icon(Icons.search),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: BorderSide.none,
                  ),
                  filled: true,
                  fillColor: Colors.white,
                ),
              ),
            ),
          ),

          // 分类标签
          SliverToBoxAdapter(
            child: Container(
              height: 50,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: _tabs.length,
                itemBuilder: (context, index) {
                  final tab = _tabs[index];
                  final isSelected = _selectedTab == tab;
                  return Container(
                    margin: const EdgeInsets.only(right: 12),
                    child: FilterChip(
                      label: Text(tab),
                      selected: isSelected,
                      onSelected: (selected) {
                        setState(() {
                          _selectedTab = tab;
                          _filterTours();
                        });
                      },
                      backgroundColor: Colors.white,
                      selectedColor: Colors.orange,
                      labelStyle: TextStyle(
                        color: isSelected ? Colors.white : Colors.black87,
                        fontWeight:
                            isSelected ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                  );
                },
              ),
            ),
          ),

          // 分类筛选
          SliverToBoxAdapter(
            child: Container(
              height: 50,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: _categories.length,
                itemBuilder: (context, index) {
                  final category = _categories[index];
                  final isSelected = _selectedCategory == category;
                  return Container(
                    margin: const EdgeInsets.only(right: 12),
                    child: FilterChip(
                      label: Text(category),
                      selected: isSelected,
                      onSelected: (selected) {
                        setState(() {
                          _selectedCategory = category;
                          _filterTours();
                        });
                      },
                      backgroundColor: Colors.white,
                      selectedColor: Colors.blue,
                      labelStyle: TextStyle(
                        color: isSelected ? Colors.white : Colors.black87,
                        fontWeight:
                            isSelected ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                  );
                },
              ),
            ),
          ),

          const SliverToBoxAdapter(child: SizedBox(height: 16)),

          // 商品列表
          _isLoading
              ? const SliverFillRemaining(
                child: Center(child: CircularProgressIndicator()),
              )
              : SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  final tour = _filteredTours[index];
                  return _buildTourCard(tour);
                }, childCount: _filteredTours.length),
              ),
        ],
      ),
    );
  }

  Widget _buildTourCard(Map<String, dynamic> tour) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          onTap: () => _showTourDetails(tour),
          borderRadius: BorderRadius.circular(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 商品图片
              ClipRRect(
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(12),
                ),
                child: Stack(
                  children: [
                    Image.network(
                      tour['image'] ?? '',
                      width: double.infinity,
                      height: 200,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: double.infinity,
                          height: 200,
                          color: Colors.grey[300],
                          child: const Icon(
                            Icons.image_not_supported,
                            size: 50,
                          ),
                        );
                      },
                    ),
                    // 分类标签
                    Positioned(
                      top: 12,
                      left: 12,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: _getCategoryColor(
                            tour['category'],
                          ).withOpacity(0.9),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          tour['category'] ?? '',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    // 热门标签
                    if (tour['isHot'] == true)
                      Positioned(
                        top: 12,
                        right: 12,
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.red.withOpacity(0.9),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: const Text(
                            'HOT',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
              // 商品信息
              Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      tour['title'] ?? '',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),

                    // 副标题
                    if (tour['subtitle'] != null && tour['subtitle'].isNotEmpty)
                      Text(
                        tour['subtitle'],
                        style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 8),

                    // 价格和销量
                    Row(
                      children: [
                        // 价格
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const Text(
                              '¥',
                              style: TextStyle(
                                color: Colors.orange,
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Text(
                              '${tour['price']}',
                              style: const TextStyle(
                                color: Colors.orange,
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(width: 4),
                            const Text(
                              '起',
                              style: TextStyle(
                                color: Colors.orange,
                                fontSize: 14,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 8),

                        // 原价
                        if (tour['originalPrice'] != null &&
                            tour['originalPrice'] > tour['price'])
                          Text(
                            '¥${tour['originalPrice']}',
                            style: const TextStyle(
                              color: Colors.grey,
                              fontSize: 14,
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),

                        const Spacer(),

                        // 销量
                        Text(
                          '已售 ${tour['soldCount']} 份',
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),

                    // 评分和评论数
                    Row(
                      children: [
                        Row(
                          children: [
                            const Icon(
                              Icons.star,
                              color: Colors.amber,
                              size: 16,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '${tour['rating'] ?? 4.5}',
                              style: const TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 8),
                        Text(
                          '${tour['reviewCount']} 条评论',
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                        const Spacer(),
                        // 预订按钮
                        ElevatedButton(
                          onPressed: () => _showTourDetails(tour),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 8,
                            ),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(6),
                            ),
                          ),
                          child: const Text(
                            '预订',
                            style: TextStyle(fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _getCategoryColor(String? category) {
    switch (category) {
      case '一日游':
        return Colors.blue;
      case '多日游':
        return Colors.green;
      case '当地游':
        return Colors.purple;
      case '自由行':
        return Colors.red;
      case '跟团游':
        return Colors.indigo;
      case '攻略群':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }
}
